package com.kerpow.tools;

import com.kerpow.KSheet.GlobalSettings;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;

public class StickyHorzScroll extends HorizontalScrollView {

	private int _scrollDelay = 250; //ms
	private boolean _enableFocus = false;
	
	private Runnable _focusView = new Runnable() {

		public void run() {
			if(_enableFocus){
				_enableFocus = false;
				focusCenterView();
			}
		}
	};
	
	public StickyHorzScroll(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public StickyHorzScroll(Context context, AttributeSet attrs) {
		super(context,attrs);
	}

	public StickyHorzScroll(Context context) {
		super(context);
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		if(GlobalSettings.snappyPowers){
		
			if(ev.getAction() == MotionEvent.ACTION_DOWN){
				this.removeCallbacks(_focusView);
				_enableFocus = false;
			}
			
			if(ev.getAction() == MotionEvent.ACTION_UP){
				this.postDelayed(_focusView, _scrollDelay);
				_enableFocus = true;
			}
		}
		return super.onTouchEvent(ev);
	}
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		this.onTouchEvent(ev);
		
		return false;
	}
	@Override
	protected void onScrollChanged(int l, int t, int oldl, int oldt) {
		this.removeCallbacks(_focusView);
		this.postDelayed(_focusView, _scrollDelay);
		
		super.onScrollChanged(l, t, oldl, oldt);
	}
    
	private void focusCenterView(){
		if(this.getChildCount() > 0){
			ViewGroup vg = (ViewGroup) this.getChildAt(0);
			if(vg.getChildCount() > 0){
				View v = vg.getChildAt(0);
				int width = v.getWidth();
				int targetPowerNum = (getScrollX() + (width / 2)) / width;
				
				this.smoothScrollTo(targetPowerNum * width, 0);
			}
		}
	}
	

}
